package com.matrix.draft.sockettest.day12;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;

public class NIOClient {

    public static int PORT = 8080;

    public static void main(String[] args) {
        for (int j = 0; j < 30; j++) {
            new Thread(() -> {
                try {
                    SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(8080));
                    socketChannel.configureBlocking(false);
                    while (!socketChannel.finishConnect()) {
                        System.out.println("正在连接服务端中...");
                    }
                    try {
                        long sequenceId = FutureKeeper.sequenceId.getAndIncrement();
                        FutureKeeper.futures.put(sequenceId,new CompletableFuture());
                        socketChannel.write(ByteBuffer.wrap(("Hello Server" + sequenceId).getBytes(StandardCharsets.UTF_8)));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    socketChannel.shutdownOutput();
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

}
